package com.kyh.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("restriction")
public class RemoteFile {
	
	private static final Logger logger = Logger.getLogger(RemoteFile.class);
	
	/**
	 * 删除文件
	 */
	public static boolean deleteFile(File file) {
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
            	logger.info("删除单个文件:"+file.getName()+" 成功！");
                return true;
            } else {
            	logger.info("删除单个文件:"+file.getName()+" 失败！");
                return false;
            }
        } else {
        	logger.info("文件不存在！");
            return false;
        }
    }
	
	/**
	 * 网络url 转换成本地文件
	 */
	public static File downUrl(String fileUrl) throws Exception {
		logger.info("开始下载远程文件.....");
		logger.info("远程文件url=====" + fileUrl);
		
		//获取系统的文件分隔符
		String separator = System.getProperty("file.separator");
		
		//判断服务器操作系统
		String tempPath = System.getProperty("java.io.tmpdir");
		if (isOSLinux() || isOSMac()) {
			tempPath = tempPath+ separator; 
		}
		
		//判断临时文件夹是否存在 不存在则创建
		File savePath = new File(tempPath);
		if (!savePath.exists()) {
			savePath.mkdir();
		}
		
		// 获取文件名
		String uname = getImgName(fileUrl);
		//获取文件后缀
		String ext = getExt(uname);
		// 创建新文件
		String tempFilePath = "";
		if (CheckUtil.notNull(ext)) {
			tempFilePath = tempPath + separator + UUID.randomUUID().toString() + "." + ext;
		} else {
			tempFilePath = tempPath + separator + UUID.randomUUID().toString();
		}
		 
		File tempfile = new File(tempFilePath);
		if (tempfile != null && !tempfile.exists()) {
			tempfile.createNewFile();
		}
		OutputStream oputstream = new FileOutputStream(tempfile);
		URL url = new URL(fileUrl);
		HttpURLConnection uc = (HttpURLConnection) url.openConnection();
		// 设置是否要从 URL 连接读取数据,默认为true
		uc.setDoInput(true);
		uc.connect();
		InputStream iputstream = uc.getInputStream();
		byte[] buffer = new byte[4 * 1024];
		int byteRead = -1;
		while ((byteRead = (iputstream.read(buffer))) != -1) {
			oputstream.write(buffer, 0, byteRead);
		}
		oputstream.flush();
		iputstream.close();
		oputstream.close();
		logger.info("下载后的本地临时文件路径=====" + tempFilePath);
		
		//图片格式统一转换为png
		File resFile = null;
		if (isImage(tempfile)) {
			String tmpStr = tempPath + separator + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
			resFile = ConverterUtil.converter(tempfile, ConverterUtil.PNG, 
					new File(tmpStr));
			logger.info("转换格式后的路径=====" + tmpStr);
		}
		
		/**
		//文件大小转换
		String imgdist = tempPath + separator + UUID.randomUUID().toString().replaceAll("-", "") + ".png";
		reduceImg(tmpStr, imgdist, 1200, 800, null);
		logger.info("转换大小后的路径=====" + imgdist);
		File reduceFile = new File(imgdist);
		
		//删除大小转换临时文件
		deleteFile(tempfile);
		*/
		if (resFile != null) {
			//删除格式转换前的临时文件
			deleteFile(tempfile);
			return resFile;
		} else {
			return tempfile;
		}
	}
	
	/**
	 * 获取文件后缀
	 */
	public static String getExt(String filename){
		//获取系统的文件分隔符
		filename = StringUtils.trimToNull(filename);
		filename = filename.replace('\\', '/');
		filename = filename.substring(filename.lastIndexOf("/") + 1);
		int index = filename.lastIndexOf(".");
		String ext = "";
		if (index >= 0) {
			ext = StringUtils.trimToNull(filename.substring(index + 1));
		}
		return ext;
	}
	
	/**
	 * 网络url 获取图片名称
	 */
	public static String getImgName(String fileUrl){
		String[] strArr = fileUrl.split("/");
		String str =strArr[strArr.length-1];
		if (str.contains("?")) {
			str = str.split("\\?")[0];
		}
		return str;
	}
	
	/**
	 * 图片宽度
	 */
	public static int[] getImgWidth(File file) throws Exception{  
        InputStream is = null;  
        BufferedImage src = null;  
        int result[] = { 0, 0 };  
        is = new FileInputStream(file);  
        src = javax.imageio.ImageIO.read(is);  
        result[0] = src.getWidth(null); // 得到源图宽  
        result[1] = src.getHeight(null); // 得到源图高  
        is.close();  
        return result;  
    }
	
	/**
	 * 判断文件是否是图片
	 */
	public static boolean isImage(File file) throws Exception{
		boolean flag = false;
		ImageInputStream is = null;
		try {
			is = ImageIO.createImageInputStream(file);
			if (null == is) {
				flag = false;
			} else {
				flag = true;
			}
		} finally {
			if (is != null) {
				is.close();
			}
		}
		return flag;
	}
	
	/**
	 * 判断是否是linux系统
	 */
	public static boolean isOSLinux() {
        Properties prop = System.getProperties();

        String os = prop.getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            return true;
        } else {
            return false;
        }
    }
	
	/**
	 * 判断是否是win系统
	 */
	public static boolean isOSWin(){
		Properties prop = System.getProperties();

        String os = prop.getProperty("os.name");
        if(os != null && os.toLowerCase().startsWith("win")){  
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 判断是否是Mac系统
	 */
	public static boolean isOSMac(){
		Properties prop = System.getProperties();
		
		String os = prop.getProperty("os.name");
		if(os != null && os.toLowerCase().startsWith("mac")){  
			return true;
		} else {
			return false;
		}
	}
	
	/** 
     * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩 
     * @param imgsrc 源图片地址 
     * @param imgdist 目标图片地址 
     * @param widthdist 压缩后图片宽度（当rate==null时，必传） 
     * @param heightdist 压缩后图片高度（当rate==null时，必传） 
     * @param rate 压缩比例  
     */ 
	public static void reduceImg(String imgsrc, String imgdist, int widthdist,  
            int heightdist, Float rate) throws Exception{  
		logger.info("开始进入图片压缩....");
		File srcfile = new File(imgsrc);
		// 检查文件是否存在
		if (!srcfile.exists()) {
			return;
		}
		// 如果rate不为空说明是按比例压缩
		if (rate != null && rate > 0) {
			// 获取文件高度和宽度
			int[] results = getImgWidth(srcfile);
			if (results == null || results[0] == 0 || results[1] == 0) {
				return;
			} else {
				widthdist = (int) (results[0] * rate);
				heightdist = (int) (results[1] * rate);
			}
		}
		// 开始读取文件并进行压缩
		Image src = javax.imageio.ImageIO.read(srcfile);
		BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
		FileOutputStream out = new FileOutputStream(imgdist);
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(tag);
		out.close();
    }  
	
	public static void main(String[] args) throws Exception{
		System.out.println(System.getProperty("java.io.tmpdir"));
		//System.out.println(isOSMac());
		//System.out.println(getImgName("http://ad4.sina.com.cn/200601/12/43932_750450.jpg"));
		System.out.println(downUrl("http://ad4.sina.com.cn/200601/12/43932_750450.jpg"));
	}
}
